package org.practice.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.practice.dao.DaoFactory;
import org.practice.dao.UserDao;
import org.practice.model.User;
import org.practice.util.Constant;
import org.practice.util.CookieUtil;

public class CartMappingDispatchAction extends MappingDispatchAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		UserDao userDao = DaoFactory.createUserDao();
		
		boolean isLogin = false;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constant.SESSION_KEY_USER);
		if (user != null) {
			isLogin = true;
		} else {
			String uid = CookieUtil.findCookie(request, Constant.COOKIE_KEY_USERID);
			if (uid != null) {
				user = userDao.findUserById(Integer.parseInt(uid));
				if (user != null) {
					session.setAttribute(Constant.SESSION_KEY_USER, user);
					isLogin = true;
				}
			}
		}
		//每次购物操作之前都要判断该用户是否已经登录过了
		if (!isLogin) {
			return mapping.findForward("loginError");
		} else {
			return super.execute(mapping, form, request, response);
		}
	}
}
